package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map search(Map<String, String> searchMap) {

        Map<String, Object> resultMap = new HashMap();

        if (searchMap != null) {
            //构建查询条件封装对象
            NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //查询1:根据搜索框的关键词进行查询
            if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }
            //查询方式2:根据品牌进行搜索过滤 brandName指定要查询的域,brand为传递的参数的键
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //查询方式3:根据规格参数进行过滤查询
            //首先获取到键的集合,然后对键的集合进行遍历
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")) {
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
                }
            }

            //查询方式4:根据价格范围进行过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))) {
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2) {
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }


            queryBuilder.withQuery(boolQuery);


            //进行品牌聚合(分组)查询
            String goodBrand = "good_Brand";
            //通过terms来绑定查询出来的分组的名称,field指定需要查询的域
            queryBuilder.addAggregation(AggregationBuilders.terms(goodBrand).field("brandName"));

            //进行参数聚合(分组)查询
            String skuSpec = "skuSpec";
            queryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //进行分页查询
            String pageNum = searchMap.get("pageNum");//获取当前页
            String pageSize = searchMap.get("pageSize");//获取每页展示的条数
            //对当前页进行非空判断,如果为空,则默认展示第一个
            if (pageNum == null) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //PageRequest.of 该方法需要两个参数
            //第一个参数为当前页,索引从0开始,所以需要进行-1的操作
            //第二个参数为每页展示的条数
            queryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));
            //进行排序查询
            if (StringUtils.isNotEmpty(searchMap.get("sortField"))) {
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    queryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                } else {
                    queryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }
            /*
            1.指定高亮域,结果就会将该域作为高亮字段的键
            2.设置高亮域前缀
            3.设置高亮域后缀
            4.在结果中获取高亮域,替换掉原name的值
            "highlight": {
          "name": [
            "华为（HUAWEI） 荣耀8X<font color='red'>手机</font> 全网通4G全面屏<font color='red'>手机</font> 幻夜黑 6G+128G"
          ]
        }
             */
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")//设置高亮域
                    .preTags("<span style='color:red'>") //设置高亮前缀
                    .postTags("</span>");
            //将高亮域作为高亮查询条件的参数
            queryBuilder.withHighlightFields(field);
            //1.开启查询
            /**
             * 第一个参数:条件构建对象
             * 第二个参数:查询操作实体类
             * 第三个参数:查询结果操作对象
             */
            AggregatedPage<SkuInfo> skuInfos = elasticsearchTemplate.queryForPage(queryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                    //对搜索结果进行处理
                    List<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    SearchHit[] hits1 = hits.getHits();
                    if (null != hits1) {
                        for (SearchHit hit : hits1) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            //获取高亮结果
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            //对获取的高亮结果进行判断,如果不为空,则替换掉原name中的值
                            /*
                              "highlight": {
                                "name": [
                                    "华为（HUAWEI） 荣耀8X<span color='red'>手机</span> 全网通4G全面屏<font color='red'>手机</font> 幻夜黑 6G+128G"
                                        ]
                                    }
                             */
                            if (highlightFields != null && highlightFields.size() > 0) {
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }
                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            //总条数
            resultMap.put("total", skuInfos.getTotalElements());
            //总页数
            resultMap.put("totalPages", skuInfos.getTotalPages());
            //查询结果集合
            resultMap.put("rows", skuInfos.getContent());

            //封装品牌的桶聚合查询结果
            StringTerms brandTerms = (StringTerms) skuInfos.getAggregation(goodBrand);
            //需要将brandTerms里面的数据封装到一个集合,使用流的循环来处理,提高效率
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);

            //封装规格的桶聚合查询结果
            StringTerms skuSpecTerms = (StringTerms) skuInfos.getAggregation(skuSpec);
            //将skuSpecTerms里面的数据进行遍历,封装到List集合中
            List<String> specList = skuSpecTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", specList);

            //返回当前页
            resultMap.put(pageNum, pageSize);
            return resultMap;
        }
        return null;
    }
}
